package org.jim.server.command.handler;

import org.apache.commons.lang3.StringUtils;
import org.jim.common.ImAio;
import org.jim.common.ImPacket;
import org.jim.common.ImSessionContext;
import org.jim.common.Protocol;
import org.jim.common.message.MessageHelper;
import org.jim.common.packets.Command;
import org.jim.common.packets.HeartbeatBody;
import org.jim.common.packets.RespBody;
import org.jim.common.packets.User;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.tio.core.ChannelContext;

/**
 *
 */
public class HeartbeatReqHandler extends AbstractCmdHandler
{
	@Override
	public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception
	{
		RespBody heartbeatBody = new RespBody(Command.COMMAND_HEARTBEAT_REQ).setData(new HeartbeatBody(Protocol.HEARTBEAT_BYTE));
		ImPacket heartbeatPacket = ImKit.ConvertRespPacket(heartbeatBody,channelContext);

		// 设置用户地理坐标
		setLocation(packet, channelContext);
		return heartbeatPacket;
	}

	private void setLocation(ImPacket packet, ChannelContext channelContext) {
		User userReq = JsonKit.toBean(packet.getBody(), User.class);
		if (StringUtils.isEmpty(userReq.getId())) {
			return;
		}
		MessageHelper messageHelper = imConfig.getMessageHelper();
		User user = messageHelper.getUserByType(userReq.getId(), 2);
		if (user == null) {
			return;
		}
		user.setExtras(userReq.getExtras());
		ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
		imSessionContext.getClient().setUser(user);
		ImAio.bindUser(channelContext, user.getId(), imConfig.getMessageHelper().getBindListener());
	}
	@Override
	public Command command() {
		return Command.COMMAND_HEARTBEAT_REQ;
	}
}
